#!/bin/sh

set -e

usage() {
    cat <<EOF
Runs a native agent with the provided git tag. Optionally, it can receive -t <tenant_id>, -s <server_address>, and -o "<KEY=VALUE>" parameters, which are used during agent initialization. If PRIVATE_KEY is not specified via -o, defaults to /tmp/shellhub-agent. Leave other parameters blank for default values.

When <tag> is '.', the agent will be built in the current Git state and named 'latest'.

Usage:
    $0 <tag> [-t <tenant_id>] [-s <server_address>] [-o <KEY=VALUE>]
Examples:
    $0 .
    $0 v0.15.0
    $0 v0.15.0 -t 00000000-0000-4000-0000-000000000000 -s http://127.0.0.1 -o "KEEPALIVE_INTERVAL=30 PREFERRED_HOSTNAME=127.0.0.2"
EOF
    exit 0
}

if [ "$#" -eq 0 ]; then
    usage
fi

. "$(dirname "$0")/utils"

tag="$1"
shift

tenant_id="00000000-0000-4000-0000-000000000000"
server_address="http://127.0.0.1"
private_key="/tmp/shellhub-agent"
additional_env=""

# Processa as flags usando getopts
while [ "$#" -gt 0 ]; do
    case "$1" in
        -t)
            tenant_id="$2"
            shift 2
            ;;
        -s)
            server_address="$2"
            shift 2
            ;;
        -o)
            additional_env="$2"
            shift 2
            ;;
        --help)
            usage
            ;;
        *)
            echo "Invalid option: $1"
            usage
            ;;
    esac
done

if [ "$tag" = "." ]; then
    tag="latest"
fi

if [ -z "$(echo "$additional_env" | grep PRIVATE_KEY)" ]; then
    if [ -n "$private_key" ]; then
        additional_env="PRIVATE_KEY=$private_key $additional_env"
    fi
fi

echo "Tenant ID: $tenant_id"
echo "Server Address: $server_address"
echo "Additional Environment Variables: $additional_env"

if [ ! -d ./bin/agent ]; then
    mkdir -p ./bin/agent
fi

if [ "$tag" = "latest" ]; then
    cd ./agent
    go build -ldflags "-X main.AgentVersion=$tag" -o "./../bin/agent/$tag"
    cd ./..
elif [ ! -f ./bin/agent/$tag ]; then
    check_bin "git"

    echo "No '$tag' agent found. Building one."

    branch=$(git symbolic-ref --short HEAD)

    (
        git checkout $tag

        cd ./agent
        go build -ldflags "-X main.AgentVersion=${tag:1}" -o "./../bin/agent/$tag" # Remove the 'v' from the beginning of the tag.
        cd ./..

        git switch $branch
    )
fi

sudo -E TENANT_ID=$tenant_id SERVER_ADDRESS=$server_address $additional_env ./bin/agent/$tag
